<?php
/**
 * Created by jinqiang on 2024/7/4 10:52.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Repository;


use App\Http\Models\Mysql\SsyAllocationIpurchaseListTable;
use App\Http\Models\Mysql\SsyAllocationIpurchaseTable;
use App\Http\Models\Mysql\SsyAllocationOrderListTable;
use App\Http\Models\Mysql\SsyAllocationOrderTable;
use App\Http\Models\Mysql\SsyAllocationSaleListTable;
use App\Http\Models\Mysql\SsyAllocationSaleTable;

class WmsRepository
{
    const ALLOCATION_CP_NUMBER = ["JC38820241021115654", "ZS68920241125152752", "ZS254520250414150642"];

    //巨沃入库回货数据
    public static function purchaseOrder($page, $limit, $startDate, $endDate, $orderCode = "")
    {
        $appkey = "dz_kz_wms";
        $secret = '1';
        $method="gwisSubQueryPurchaseOrderConfirm";
        $url = "http://118.31.6.97:19012/gids/Gwms/WMSService?method=".$method."&appkey=".$appkey."&secret=".$secret."&format=JSON";
        $data = [
            'startDate' => $startDate,
            'endDate' => $endDate,
            'page' => $page,
            'pageSize' => $limit
        ];
        if(!empty($orderCode)){
            $data['sourceCode'] = $orderCode;
        }
        $data= json_encode($data,JSON_UNESCAPED_UNICODE);
        //dump($data);
        $param = [
            'json' => $data,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($data)]
        ];
        $resp = httpCurl($url, $param);
        return json_decode($resp, true);
    }

    //加工单手动完结、调拨单取消计划
    public static function cancel($orderCode, $orderType = "CGRK", $goodsOwner = "SSY")
    {
        $appkey = "dz_kz_wms";
        $secret = '1';
        $method="gwisSubCancelOrder";
        $url = "http://118.31.6.97:19012/gids/Gwms/WMSService?method=".$method."&appkey=".$appkey."&secret=".$secret."&format=JSON";
        $data = [
            'orderCode' => $orderCode,
            'orderType' => $orderType,
            'goodsOwner' => $goodsOwner,
        ];
        $data= json_encode($data,JSON_UNESCAPED_UNICODE);
        $param = [
            'json' => $data,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($data)]
        ];
        $resp = httpCurl($url, $param);
        return json_decode($resp, true);
    }

    //推送加工厂
    public static function pushFactory($factoryObj)
    {
        $appkey="dz_kz_wms";
        $secret = '1';
        $method="gwisSubSupplierCreateOrUpdate";
        $url="http://118.31.6.97:19012/gids/Gwms/WMSService?method=".$method."&appkey=".$appkey."&secret=".$secret."&format=JSON";
        $status = $factoryObj['status'] ?: 1;
        $data = [
            'items' => [
                [
                    "supplierCode"=>$factoryObj['supplier_id'],
                    "supplierName"=>$factoryObj['factory_name'],
                    "supplierAbbreviation"=>$factoryObj['factory_name_jiancheng'],
                    "phone"=>$factoryObj['contact_phone'],
                    "linkman"=>$factoryObj['legal_person'],
                    "address"=>$factoryObj['contact_address'],
                    "supplierType"=>$factoryObj['group'],
                    "state"=>$status,
                    "remark"=>$factoryObj['remark']
                ]
            ]
        ];
        $data= json_encode($data,JSON_UNESCAPED_UNICODE);
        $param = [
            'json' => $data,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($data)]
        ];
        $resp = httpCurl($url, $param);
        return json_decode($resp, true);
    }

    //推送吊牌信息
    public static function pushTag($data)
    {
        $appkey = "dz_kz_wms";
        $secret = '1';
        $method = "gwisSubGoodsCreateOrUpadte";
        $url = "http://118.31.6.97:19012/gids/Gwms/WMSService?method=".$method."&appkey=".$appkey."&secret=".$secret."&format=JSON";
        $data= json_encode($data,JSON_UNESCAPED_UNICODE);
        $param = [
            'json' => $data,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($data)]
        ];
        $resp = httpCurl($url, $param);
        return json_decode($resp, true);
    }

    //推送rfid
    public static function pushIFid($data)
    {
        $appkey = "dz_kz_wms";
        $secret = '1';
        $method = "gwisSubSyncBatchGoodsIDCodeInfo";
        $url = "http://118.31.6.97:19012/gids/Gwms/WMSService?method=".$method."&appkey=".$appkey."&secret=".$secret."&format=JSON";
        $data= json_encode($data,JSON_UNESCAPED_UNICODE);
        $param = [
            'json' => $data,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($data)]
        ];
        $resp = httpCurl($url, $param);
        return json_decode($resp, true);
    }

    //推送调拨单(借赠还)
    public static function pushAllocation($allocationNumber, $sub)
    {
        //杭州次品仓 调拨单据
        $allocationNumberCPList = self::ALLOCATION_CP_NUMBER;
        $allocationObj = (new SsyAllocationOrderListTable())->where('allocation_number', $allocationNumber)->first()->toArray();
        if(!in_array($allocationObj['groups'], [1, 2, 3, 4])){
            return ['code' => -1, 'msg' => '单据类型未知'];
        }
        if($allocationObj['is_push'] == 1){
            return ['code' => -1, 'msg' => '当前单据已推送,无需重复推送'];
        }
        if($allocationObj['groups'] == 1){//赠送
            list($sourceType, $fromWhcode, $targetWhcode) = ["01", "HZC", "DBZ"];
            if(in_array($allocationNumber, $allocationNumberCPList)){ //杭州次品仓赠送
                list($sourceType, $fromWhcode, $targetWhcode) = ["01", "HZCPC", "DBZ"];
            }
        }
        if(in_array($allocationObj['groups'], [2, 4])){//2借出 4销售
            list($sourceType, $fromWhcode, $targetWhcode) = ["01", "HZC", "DBJ"];
            if(in_array($allocationNumber, $allocationNumberCPList)){ //杭州次品仓借出
                list($sourceType, $fromWhcode, $targetWhcode) = ["01", "HZCPC", "DBJ"];
            }
        }
        if($allocationObj['groups'] == 3){//归还
            list($sourceType, $fromWhcode, $targetWhcode) = ["02", "DBJ", "XTC"];
            if(in_array($allocationObj['source_allocation_number'], $allocationNumberCPList)){ //杭州次品仓借出
                list($sourceType, $fromWhcode, $targetWhcode) = ["01", "DBJ", "HZCPC"];
            }
            $str=substr($allocationNumber,0,3);
            if($str == 'SZH'){//送转还
                list($sourceType, $fromWhcode, $targetWhcode) = ["01", "DBZ", "XTC"];
                if(in_array($allocationObj['source_allocation_number'], $allocationNumberCPList)){ //杭州次品仓赠送
                    list($sourceType, $fromWhcode, $targetWhcode) = ["01", "DBZ", "HZCPC"];
                }
            }
        }
        $detail = [];
        $allocationOrders = (new SsyAllocationOrderTable())->where('allocation_number', $allocationNumber)->get(['sku_code', 'num'])->toArray();
        foreach ($allocationOrders as $item){
            $detail[] = ['sku' => $item['sku_code'], 'qty' => $item['num']];
        }
        $subjects = array_column(config("scm.subject"), "owner_code", "is_subject");
        $data = [
            "head" => [
                "orderCode" => $allocationNumber,//调拨计划号
                "sourceOrderNo" => $allocationNumber,//来源单号
                "sourceType" => $sourceType,//来源类型
                "fromWhcode" => $fromWhcode,//调出仓库编码
                "targetWhcode" => $targetWhcode,//调入仓库编码
                "createUserName" => $allocationObj['adduser'],//创建人编码
                "goodsOwner" => $subjects[$allocationObj['is_subject'] ?: $sub],//调货主
                "logisticsCompanyCode" => $allocationObj['logistics_company_code'],//物流商编码
                "expressNo" => $allocationObj['ourier_number'],
                "remark" => $allocationObj['remark'],
                "wpPhon" => $allocationObj['wp_phone'],
                "wpProv" => $allocationObj['wp_province'],
                "wpreca" => $allocationObj['wp_user'],
                "wpCity" => $allocationObj['wp_city'],
                "wpCounty" => $allocationObj['wp_area'],
                "wpAddr" => $allocationObj['wp_address'],
                "detailList" => $detail//调拨sku列表
            ]
        ];
        $appkey = "dz_kz_wms";
        $secret = '1';
        $method = "gwisSubCreateTranPlan";
        $url = "http://118.31.6.97:19012/gids/Gwms/WMSService?method=".$method."&appkey=".$appkey."&secret=".$secret."&format=JSON";
        $data= json_encode($data,JSON_UNESCAPED_UNICODE);
        $param = [
            'json' => $data,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($data)]
        ];
        $resp = httpCurl($url, $param);
        $res = json_decode($resp, true);
        $isPush = $res['success'] === true ? 1 : 2;
        (new SsyAllocationOrderListTable())->updateDataWhere(['allocation_number' => $allocationNumber], ['is_push' => $isPush]);
        return $isPush == 1 ? ['code' => 0, 'msg' => '推送调拨计划成功', 'data' => $res] : ['code' => -1, 'msg' => '推送调拨计划失败', 'data' => $res];
    }

    //DBJ仓库(借出转销售、借出转内购)
    public static function pushAllocationS($allocationNumber, $sub)
    {
        $isJZX = str_starts_with($allocationNumber, "JZX") ? true : false;
        if($isJZX){
            $allocationObj = (new SsyAllocationSaleListTable())->where('allocation_number', $allocationNumber)->first()->toArray();
            $allocationList = (new SsyAllocationSaleTable())->where('allocation_number', $allocationNumber)->get()->toArray();
        }else{
            $allocationObj = (new SsyAllocationIpurchaseListTable())->where('allocation_number', $allocationNumber)->first()->toArray();
            $allocationList = (new SsyAllocationIpurchaseTable())->where('allocation_number', $allocationNumber)->get()->toArray();
        }
        list($sourceType, $fromWhcode, $targetWhcode) = ["03", "DBJ", ""];
        foreach ($allocationList as $item){
            $detail[] = ['sku' => $item['sku_code'], 'qty' => $item['num']];
        }
        $subjects = array_column(config("scm.subject"), "owner_code", "is_subject");
        $data = [
            "head" => [
                "orderCode" => $allocationNumber,//调拨计划号
                "sourceOrderNo" => $allocationNumber,//来源单号
                "sourceType" => $sourceType,//来源类型
                "fromWhcode" => $fromWhcode,//调出仓库编码
                "targetWhcode" => $targetWhcode,//调入仓库编码
                "createUserName" => $allocationObj['adduser'],//创建人编码
                "goodsOwner" => $subjects[$allocationObj['is_subject'] ?: $sub],//调货主
                "remark" => $allocationObj['reason'] ?? "",
                "detailList" => $detail//调拨sku列表
            ]
        ];
        $appkey = "dz_kz_wms";
        $secret = '1';
        $method = "gwisSubCreateTranPlan";
        $url = "http://118.31.6.97:19012/gids/Gwms/WMSService?method=".$method."&appkey=".$appkey."&secret=".$secret."&format=JSON";
        $data= json_encode($data,JSON_UNESCAPED_UNICODE);
        $param = [
            'json' => $data,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($data)]
        ];
        $resp = httpCurl($url, $param);
        $res = json_decode($resp, true);
        $isPush = $res['success'] === true ? 1 : 2;
        if($isJZX){
            (new SsyAllocationSaleListTable())->updateData($allocationObj['id'], ['is_push' => $isPush]);
        }else{
            (new SsyAllocationIpurchaseListTable())->updateData($allocationObj['id'], ['is_push' => $isPush]);
        }

        return $isPush == 1 ? ['code' => 0, 'msg' => '推送调拨计划成功', 'data' => $res] : ['code' => -1, 'msg' => '推送调拨计划失败', 'data' => $res];
    }

    //IBOX入库推送接口
    public static function pushStock($data)
    {
        $appkey = "dz_kz_wms";
        $secret = '1';
        $method = "gwisSubSyncInStockData";
        $url = "http://118.31.6.97:19012/gids/Gwms/WMSService?method=".$method."&appkey=".$appkey."&secret=".$secret."&format=JSON";
        $data= json_encode($data,JSON_UNESCAPED_UNICODE);
        $param = [
            'json' => $data,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($data)]
        ];
        $resp = httpCurl($url, $param);
        return json_decode($resp, true);
    }
}
